/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.me.message;

import java.util.ArrayList;
import java.util.List;

import com.cenluan.user.User;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

/**
 * 留言，消息
 * 
 * @author peak
 * 
 */
public class Message extends Model<Message> {

	private static final long serialVersionUID = 1L;

	public static final Message dao = new Message();

	/**
	 * 获取接收消息的用户
	 * 
	 * @return
	 */
	public User getToUser() {
		return User.dao.findById(getStr("toUserId"));
	}

	/**
	 * 获取发送消息的用户
	 * 
	 * @return
	 */
	public User getFromUser() {
		return User.dao.findById(getStr("fromUserId"));
	}

	/**
	 * 分页查询用户的对话
	 * 
	 * @param pn
	 * @param pz
	 * @param userId
	 * @param contactsId
	 *            联系人ID
	 * @return
	 */
	public Page<Message> paginateUserDialog(int pn, int pz, String userId,
			String contactsId) {
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		sql.append(" from t_message ");
		sql.append(" where ((toUserId=? and fromUserId=?) ");
		paras.add(userId);
		paras.add(contactsId);
		sql.append("  or (toUserId=? and fromUserId=?)) ");
		paras.add(contactsId);
		paras.add(userId);
		sql.append(" and deletedUserId!=? ");
		paras.add(userId);
		sql.append(" order by createTime desc ");
		return paginate(pn, pz, "select *", sql.toString(), paras.toArray());

	}

	/**
	 * 分页查询用户的收件箱，每个联系人的消息只出现最后那条
	 * 
	 * @param p
	 * @param pz
	 * @param userId
	 * @return
	 */
	public Page<Message> paginateUserInbox(int p, int pz, String userId) {
		// TODO 明天继续
		return null;
	}

}
